package cn.com.yd.commons.grpc.config;

import io.grpc.BindableService;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import java.io.IOException;
/**
 * Grpc Server
 * @author 李庆海
 *
 */
public class GrpcServer {
	/** 服务器*/
    private Server server;

    public GrpcServer(boolean ssl, int port, Object... services) {
        try {
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            //初始化Server参数
            ServerBuilder builder = ServerBuilder.forPort(port);
            //如果需要SSL
            if (ssl) {
                builder.useTransportSecurity(ssc.certificate(), ssc.privateKey());
            }
            for (Object bs : services) {
                builder.addService((BindableService) bs);
            }
            server = builder.build();
        } catch (Exception e) {
            e.printStackTrace();
            server = null;
        }
    }

    /**
     * 启动服务
     */
    public void start() throws IOException {
        if (null != server) {
            server.start();
            System.out.println("Server started, listening on " + server.getPort());
            //程序退出时关闭资源
            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                System.err.println("*** shutting down gRPC server since JVM is shutting down");
                GrpcServer.this.stop();
                System.err.println("*** server shut down");
            }));
        }
    }

    /**
     * 关闭服务
     */
    public void stop() {
        if (server != null) {
            server.shutdown();
        }
    }

    /**
     * 使得server一直处于运行状态
     */
    public void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }
}
